﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using App1AppHandler;
using System.Data.SqlClient;
using Reborn_WorldServer;
using System.Diagnostics;

namespace Reborn_Server.App1AppHandler
{
    public class BankManager
    {
        private Character MyCharacter;

        private List<Loot> _BankItems = new List<Loot>();
        
        private int _BankCoins = 0;
        public int BankCoins
        {
            set
            {
                lock (_BankItems)
                {
                    _BankCoins = value;
                }
            }
            get
            {
                lock (_BankItems)
                {
                    return _BankCoins;
                }
            }
        }

        public BankManager(Character myCharacter)
        {
            MyCharacter = myCharacter;

            //LOAD ITEMS
            SqlConnection MyCon = new SqlConnection(Managers.DBConnectionString);
            SqlCommand SQLCom = new SqlCommand("Characters_Banks_Select", MyCon);
            SQLCom.CommandType = System.Data.CommandType.StoredProcedure;
            SQLCom.Parameters.AddWithValue("@CharacterID", MyCharacter.ID);

            MyCon.Open();
            SqlDataReader SDR = SQLCom.ExecuteReader();

            while (SDR.Read())
            {
                Loot bankItem = MyCharacter.GameHandler.CreateItem(int.Parse(SDR["ItemID"].ToString()));
                //Debug.Print(bankItem.Name + " " + bankItem.ID);

                if (SDR["Item_BoundTo"] != DBNull.Value)
                    bankItem.BoundTo = int.Parse(SDR["Item_BoundTo"].ToString());

                _BankItems.Add(bankItem);
            }
            SDR.Close();
            SDR.Dispose();

            MyCon.Close();
            MyCon.Dispose();
        }

        public List<Loot> getBankCopy()
        {
            List<Loot> result = new List<Loot>();
            lock (_BankItems)
            {
                foreach (Loot bankItem in _BankItems)
                    result.Add(bankItem);
            }
            return result;
        }

        public Loot getItem(long gameUID)
        {
            lock (_BankItems)
            {
                foreach (Loot bankItem in _BankItems)
                {
                    if (bankItem.GameUID == gameUID)
                        return bankItem;
                }
            }
            return null;
        }

        public bool removeItem(Loot itemToRemove)
        {
            lock (_BankItems)
            {
                bankChanged = true;
                return _BankItems.Remove(itemToRemove);
            }
        }
        public Loot removeItem(long gameUID)
        {
            lock (_BankItems)
            {
                foreach (Loot bankItem in _BankItems)
                {
                    if (bankItem.GameUID == gameUID)
                    {
                        _BankItems.Remove(bankItem);
                        bankChanged = true;
                        return bankItem;
                    }
                }
            }
            return null;
        }

        //Counts the number of occurances of item with matching itemID. Must be bound to me or un-bound (-1)
        public int countItems(int itemId)
        {
            int result = 0;

            lock (_BankItems)
            {
                foreach (Loot loot in _BankItems)
                {
                    if (loot.ID == itemId &&
                        (loot.BoundTo == -1 || loot.BoundTo == MyCharacter.ID))
                    {
                        result++;
                    }
                }
            }

            return result;
        }

        public void depositItem(Loot itemToDeposit)
        {
            lock (_BankItems)
            {
                _BankItems.Add(itemToDeposit);
                bankChanged = true;
            }
        }

        private bool bankChanged = false;
        public void SaveBank()
        {
            lock (_BankItems)
            {
                if (bankChanged == false)
                    return;
                else
                    bankChanged = false;

                SqlConnection MyCon = new SqlConnection(Managers.DBConnectionString);
                MyCon.Open();
                SqlTransaction MyTrans = MyCon.BeginTransaction();

                SqlCommand SQLCom = new SqlCommand();
                SQLCom.Connection = MyCon;
                SQLCom.CommandType = System.Data.CommandType.StoredProcedure;
                SQLCom.Transaction = MyTrans;

                try
                {
                    //Delete existing items from bank
                    SQLCom.CommandText = "Characters_Banks_Delete";
                    SQLCom.Parameters.AddWithValue("@CharacterID", MyCharacter.ID);
                    SQLCom.ExecuteNonQuery();

                    //Add new items to bank
                    SQLCom.CommandText = "Characters_Banks_Insert";
                    //Character ID already exists from above query
                    SQLCom.Parameters.Add("@ItemID", System.Data.SqlDbType.Int);
                    SQLCom.Parameters.Add("@Item_BoundTo", System.Data.SqlDbType.Int);
                    foreach (Loot loot in _BankItems)
                    {
                        SQLCom.Parameters["@ItemID"].Value = loot.ID;
                        SQLCom.Parameters["@Item_BoundTo"].Value = loot.BoundTo;

                        SQLCom.ExecuteNonQuery();
                    }

                    MyTrans.Commit();
                }
                catch
                {
                    MyTrans.Rollback();
                }
                finally
                {
                    MyCon.Close();
                    MyCon.Dispose();
                }
            }
        }
    }
}
